package com.qiall.bashutil;


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import ch.ethz.ssh2.channel.ChannelManager;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Scanner;

public class SshScripUtil {

    private static String DEFAULTCHART = "UTF-8";

    public static Connection login(String ip, String user, String password) throws Exception {
        //创建远程连接，默认连接端口为22，如果不使用默认，可以使用方法
        try {
            Connection connection = new Connection(ip);// 创建对象
            connection.connect();
            //使用用户名和密码登录 有秘钥可以使用authenticateWithPublicKey验证
            boolean isSuccess = connection.authenticateWithPassword(user, password);
            if (!isSuccess) {
                throw new Exception("ssh auth fail check password and user name");
            }
            return connection;

        } catch (IOException e) {
            throw new Exception("connect fail" + e.getMessage());
        }

    }

    /**
     * 远程执行shll脚本或者命令
     *
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    public static String execute(Connection connection, String cmd) throws Exception {
        String result = "";
        try {
            Session session = connection.openSession();//打开一个会话
            session.execCommand(cmd);//执行命令
            result = processStdout(session.getStdout(), DEFAULTCHART);

            if (StringUtils.isBlank(result)) {
                result = processStdout(session.getStderr(), DEFAULTCHART);
            } else {
            }
            connection.close();
            session.close();

        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }
        return result;
    }

    public static Connection execCommand(Connection connection, String cmd) {
        String result = "";
        try {
            Session session=connection.openSession();
            session.execCommand(cmd);//执行命令
            result = processStdout(session.getStdout(), DEFAULTCHART);

            if (StringUtils.isBlank(result)) {
                result = processStdout(session.getStderr(), DEFAULTCHART);
            }
            System.out.println(result);
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }


    private static String processStdout(InputStream in, String charset) throws Exception {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + " ");
            }
        } catch (UnsupportedEncodingException e) {
            throw new Exception(e.getMessage());

        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }
        return buffer.toString();
    }




}



